/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package heartsclient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JOptionPane;

/**
 *
 * @author PeterNguyen
 */
public class Client implements Runnable {

    private int first = 1;
    private Socket socket = null;
    private Thread thread = null;
    private DataInputStream console = null;
    private DataOutputStream streamOut = null;
    private ThreadClient client = null;
    //  public static GameStateTableCard tableCard;
    public CuaSoGame cuaSoGame;
    public int num = -1;
    public int type = -1;
    public String[] baiDuocChia = new String[13];
    public static int[] baichia = new int[27];
    frmDiem hienThiDiem = new frmDiem(this);
    public int soTran = 1;
    int Cardcount = 0;
    public int currentPlayer = -1;
    public int startPlayer = -1;

    public Client(String serverName, int serverPort) {
        System.out.println("Establishing connection. Please wait ...");
        try {
            socket = new Socket(serverName, serverPort);
            System.out.println("Connected: " + socket);
            cuaSoGame = new CuaSoGame(this);
            cuaSoGame.setVisible(true);
            start();
        } catch (UnknownHostException uhe) {
            System.out.println("Host unknown: " + uhe.getMessage());
        } catch (IOException ioe) {
            System.out.println("Unexpected exception: " + ioe.getMessage());
        }
    }

    @Override
    public void run() {
        while (thread != null) {
            try {
                streamOut.writeUTF(console.readLine());
                streamOut.flush();
            } catch (IOException ioe) {
                System.out.println("Sending error: " + ioe.getMessage());
                stop();
            }
        }
    }

    public void send(String msg) {

        try {
            streamOut.writeUTF(msg);
            streamOut.flush();
        } catch (IOException ioe) {
            System.out.println("Sending error: " + ioe.getMessage());
            stop();
        }

    }
    //Ham xu ly doi bai: Cap nhat lai trang thai cua quan bai (doi info cua nguoi choi)

    public void XuLyNhanBai(String msg) {
        System.out.print("\nsent message " + msg);
        String[] parameterArray = msg.split(" ");
        int code = Integer.parseInt(parameterArray[0]);
        String sentMsg;

        switch (code) {
            case 5:
                hienThiDiem.addDiem(parameterArray);
                break;
            case 6: //Nhan bai duoc chia         
                //        System.out.println("So luong: " + parameterArray.length);
                int i;
                if (parameterArray.length < 28) {
                    //Thông báo tới lượt đi
                    cuaSoGame.toiLuotDi();
                    System.out.println("Nguoi choi bat dau: "
                            + parameterArray[0] + " " + parameterArray[1]);
                } else {
                    //Nhan 13 la bai
                    cuaSoGame.dsCardPlayer.clear();
                    currentPlayer = Integer.parseInt(parameterArray[1]);
                    i = 2;
                    for (; i < parameterArray.length; i = i + 2) {
                        //System.out.println(baiDuocChia[i] + " ");
                        baichia[i - 2] = Integer.valueOf(parameterArray[i]);
                        baichia[i - 1] = Integer.valueOf(parameterArray[i + 1]);
                        QuanBai card = new QuanBai(baichia[i - 2], baichia[i - 1], currentPlayer);
                        cuaSoGame.dsCardPlayer.add(card);
                    }
                    System.out.printf("\nBai duoc chia player %d :%d length ",currentPlayer , baichia.length);
                    for (i = 0; i < baichia.length - 1; i++) {
                        System.out.print(baichia[i] + " ");
                    }
                    cuaSoGame.PlayerID = currentPlayer;
                    cuaSoGame.setTitle("Player "+currentPlayer);
                    cuaSoGame.showcard();
                }
                break;
            case 7://Gưi thông tin bài đánh ra của player khác
                int player = Integer.parseInt(parameterArray[1]);
                int number = Integer.parseInt(parameterArray[2]);
                int type = Integer.parseInt(parameterArray[3]);
                cuaSoGame.baiNguoiChoi(number, type, player);
                break;
            case 12: //Doi bai
                for (i = 2; i < parameterArray.length; i = i + 2) {
                    //System.out.println(baiDuocChia[i] + " ");     
                    int so = Integer.valueOf(parameterArray[i]);
                    int dang = Integer.valueOf(parameterArray[i + 1]);
                    QuanBai card = new QuanBai(so, dang, currentPlayer);
                    cuaSoGame.dsCardPlayer.add(card);
                }
                cuaSoGame.showBaiSauDoi();
                cuaSoGame.viTriHaiChuon();
                break;
        }

    }

    public void start() throws IOException {
        console = new DataInputStream(System.in);
        streamOut = new DataOutputStream(socket.getOutputStream());
        if (thread == null) {
            client = new ThreadClient(this, socket);
            thread = new Thread(this);
            thread.start();
        }
    }

    public void stop() {
        if (thread != null) {
            thread.stop();
            thread = null;
        }
        try {
            if (console != null) {
                console.close();
            }
            if (streamOut != null) {
                streamOut.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException ioe) {
            System.out.println("Error closing ...");
        }
        client.close();
        client.stop();
    }

    public int KiemTraLaBai(QuanBai BaiDanh, QuanBai BaiDauTien) {
        int flag = 1; //Quan bai thoa dieu kien
        if (BaiDanh.type != BaiDauTien.type) {
            flag = 0;
        }

        return flag;

    }

    public int NguoiChoiGomBai(ArrayList<QuanBai> lstQuanBai) {
        int flag = 0;
        if (lstQuanBai.size() > 0) {
            for (int i = 0; i < lstQuanBai.size(); i++) {
                //Kiem tra do thang cua quan bai
            }
        }
        return flag;
    }
    static String iPort;
    static String sIP;

    public static void main(String args[]) {
        Client client = null;
        //Set port and ip test
        iPort = "8888";
        sIP = "192.168.2.2";
        sIP = JOptionPane.showInputDialog("IP server (tam thoi): ");
        iPort = JOptionPane.showInputDialog("Port (tam thoi): ");

        if (iPort != null && sIP != null) {
            client = new Client(sIP, Integer.parseInt(iPort));
        }

    }
}
